package com.vision.sales.creditmemo.cl.ui;

import static com.vision.sales.cl.SalesServices.companySvc;
import static com.vision.sales.cl.SalesServices.creditMemoSvc;
import static com.vision.sales.cl.SalesServices.customerSvc;

import java.util.ArrayList;
import java.util.List;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.Style.SelectionMode;
import com.sencha.gxt.data.client.loader.RpcProxy;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.Store;
import com.sencha.gxt.data.shared.loader.LoadEvent;
import com.sencha.gxt.data.shared.loader.LoadResultListStoreBinding;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoader;
import com.sencha.gxt.widget.core.client.TabItemConfig;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.event.HideEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.form.DateField;
import com.sencha.gxt.widget.core.client.form.NumberField;
import com.sencha.gxt.widget.core.client.form.NumberPropertyEditor;
import com.sencha.gxt.widget.core.client.form.SimpleComboBox;
import com.sencha.gxt.widget.core.client.form.StoreFilterField;
import com.sencha.gxt.widget.core.client.form.TextArea;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.form.validator.MaxLengthValidator;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.GridView;
import com.sencha.gxt.widget.core.client.menu.CheckMenuItem;
import com.sencha.gxt.widget.core.client.menu.Item;
import com.sencha.gxt.widget.core.client.menu.MenuItem;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent.SelectionChangedHandler;
import com.sencha.gxt.widget.core.client.toolbar.PagingToolBar;
import com.vision.core.cl.BaseModule;
import com.vision.core.cl.Callback;
import com.vision.core.cl.event.CreatedEvent;
import com.vision.core.cl.event.CreatedEvent.CreationHandler;
import com.vision.core.cl.ui.ConfirmDialogHandler;
import com.vision.core.cl.ui.Notifications;
import com.vision.core.cl.ui.TabItemPanel;
import com.vision.core.cl.ui.UI;
import com.vision.core.cl.ui.component.BasicGridView;
import com.vision.core.cl.ui.component.BasicPagingLoader;
import com.vision.core.cl.ui.component.CompanyComboBox;
import com.vision.core.cl.ui.component.EnumComboBox;
import com.vision.core.cm.db.data.Company;
import com.vision.sales.cl.SalesServices;
import com.vision.sales.cl.SalesTasks;
import com.vision.sales.cl.data.CreditMemoProperties;
import com.vision.sales.cl.event.CreditMemoCreatedEvent;
import com.vision.sales.cl.resource.SalesResources;
import com.vision.sales.cl.ui.component.CustomerComboBox;
import com.vision.sales.cl.ui.component.SalesInvoiceComboBox;
import com.vision.sales.cl.ui.component.TransactionLoadConfig;
import com.vision.sales.cl.ui.component.TransactionNoCell;
import com.vision.sales.cm.data.CreditMemoType;
import com.vision.sales.cm.data.DataUtils;
import com.vision.sales.cm.data.TransactionStatus;
import com.vision.sales.cm.db.data.CreditMemo;
import com.vision.sales.cm.db.data.CreditMemo.FieldSpecs;
import com.vision.sales.cm.db.data.Customer;

public class CreditMemosPanel extends TabItemPanel implements Editor<CreditMemo> {

	interface Binder extends UiBinder<Widget, CreditMemosPanel> { }

	private static final Binder binder = GWT.create(Binder.class);
	
	@UiField VerticalLayoutContainer mainPanel;
	
	// Ignored by the form driver since these are not fields in the CreditMemo
	@Ignore @UiField StoreFilterField<CreditMemo> gridFilter;
	@Ignore @UiField TextButton filterBtn;
	@Ignore @UiField MenuItem statusMenuItem;
		@Ignore @UiField CheckMenuItem pendingOnlyMenuItem;
		@Ignore @UiField CheckMenuItem postedOnlyMenuItem;
		@Ignore @UiField CheckMenuItem allStatusMenuItem;
	
	@Ignore @UiField TextButton addBtn;
	@Ignore @UiField TextButton postBtn;
	@Ignore @UiField TextButton moreBtn;
	@Ignore @UiField MenuItem refreshMenuItem;
	@Ignore @UiField MenuItem deleteMenuItem;
	
	@UiField(provided = true) NumberFormat numberFormat = UI.amountFormat();
	@UiField(provided = true) NumberPropertyEditor<Double> doublePropertyEditor = UI.doubleEditor();
	
	@UiField Grid<CreditMemo> grid;
	@UiField PagingToolBar pagingToolbar;
	PagingLoader<PagingLoadConfig, PagingLoadResult<CreditMemo>> loader;
	
	// Form fields that are bound by the form driver to the fields in the CreditMemo class.
	// The name of these form fields must match the name of the field in the CreditMemo class.
	@UiField TextField creditMemoNo;
	@UiField DateField date;
	@UiField NumberField<Double> amount;
	@UiField CustomerComboBox customer;
	@UiField SalesInvoiceComboBox salesInvoice;
	@UiField CompanyComboBox company;
	@UiField SimpleComboBox<CreditMemoType> type;
	@UiField TextArea remarks;
	
	// Ignored by the form driver since these are not fields in the CreditMemo
	@Ignore @UiField TextButton saveBtn;
	@Ignore @UiField TextButton cancelBtn;
	
	// Interface used to bind the form fields to the CreditMemo fields
	interface CreditMemoDriver extends SimpleBeanEditorDriver<CreditMemo, CreditMemosPanel> { }
	
	// Instance of the CreditMemoDriver interface
	private CreditMemoDriver driver = GWT.create(CreditMemoDriver.class);
	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	public CreditMemosPanel() {
		// Global Handlers -- should be registered only once
		BaseModule.addHandler(CreditMemoCreatedEvent.TYPE, new CreationHandler<CreditMemo>() {
			@Override
			public void onCreated(CreatedEvent<CreditMemo> e) {
				grid.getStore().add(e.getObject());
			}
		});
		
		setWidget(binder.createAndBindUi(this));
		
		// Bind the filter into the grid's store
		gridFilter.bind(grid.getStore());
		
		date.setPropertyEditor(UI.datePropertyEditor());
		salesInvoice.setHideTrigger(true);
		
		// Initialize loaders
		RpcProxy<PagingLoadConfig, PagingLoadResult<CreditMemo>> proxy = new RpcProxy<PagingLoadConfig, PagingLoadResult<CreditMemo>>() {
		    @Override
		    public void load(PagingLoadConfig loadConfig, AsyncCallback<PagingLoadResult<CreditMemo>> callback) {
		    	TransactionLoadConfig tConfig = new TransactionLoadConfig(loadConfig);
		    	setFilterInfo(tConfig);
		    	SalesServices.creditMemoSvc().getList(tConfig, callback);
		    }
	    };
	    
	    loader = new BasicPagingLoader<CreditMemo>(proxy, grid.getStore());
        loader.addLoadHandler(new LoadResultListStoreBinding<PagingLoadConfig, CreditMemo, PagingLoadResult<CreditMemo>>(grid.getStore()) {
        	@Override
        	public void onLoad(LoadEvent<PagingLoadConfig, PagingLoadResult<CreditMemo>> event) {
        		super.onLoad(event);
        		grid.getSelectionModel().deselectAll();
        		edit(null);
        	}
        });
        
        grid.setLoader(loader);
        grid.setLoadMask(true);
		
		pagingToolbar.bind(loader);
		
		// Initialize the driver, used to run the form editor
		driver.initialize(this);
		
		creditMemoNo.addValidator(new MaxLengthValidator(FieldSpecs.CM_NO_MAX));
		remarks.addValidator(new MaxLengthValidator(FieldSpecs.REMARKS_MAX));
	}
		
	// UiFactory Methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	@Ignore
	@UiFactory
	SimpleComboBox<CreditMemoType> initializeCreditMemoTypeCombo() {
		return new EnumComboBox<CreditMemoType>(CreditMemoType.values());
	}
	
	@Ignore
	@UiFactory
	StoreFilterField<CreditMemo> initializeGridFilter() {
		StoreFilterField<CreditMemo> f = new StoreFilterField<CreditMemo>() {
			@Override
			protected boolean doSelect(Store<CreditMemo> store, CreditMemo parent, CreditMemo item, String filter) {
				String filterInLowerCase = filter.toLowerCase().trim();
				return item.getCreditMemoNo().toLowerCase().contains(filterInLowerCase);
			}
		};
		return f;
	}

	/**
	 * Used to create the 'grid' field in the XML file. 
	 * 
	 * @return
	 */
	@UiFactory
	Grid<CreditMemo> initializeGrid() {
		CreditMemoProperties props = CreditMemoProperties.INSTANCE;
		
		List<ColumnConfig<CreditMemo, ?>> columns = new ArrayList<ColumnConfig<CreditMemo, ?>>();
		ListStore<CreditMemo> store = new ListStore<CreditMemo>(props.key());

		columns.add(UI.column(props.date(), 50, "Date", UI.dateCell()));
		columns.add(UI.column(props.companyCode(), 50, "Company"));
		columns.add(UI.column(props.creditMemoNo(), 70, "C/M No.", new TransactionNoCell<CreditMemo>(store)));
		columns.add(UI.column(props.type(), 70, "C/M Type"));
		ColumnConfig<CreditMemo, String> column = UI.column(props.customerCode(), 100, "Customer");
		columns.add(column);
		columns.add(UI.column(props.salesInvoiceNo(), 70, "Invoice No."));
		columns.add(UI.column(props.amount(), 80, "Amount", UI.decimalCell(), HasHorizontalAlignment.ALIGN_RIGHT));
//		columns.add(UI.column(props.status(), 50, "Status", TransactionStatusCell.INSTANCE, HasHorizontalAlignment.ALIGN_CENTER));
		
		ColumnModel<CreditMemo> cm = new ColumnModel<CreditMemo>(columns);

		final Grid<CreditMemo> grid = new Grid<CreditMemo>(store, cm);
		grid.setAllowTextSelection(false);
		grid.getSelectionModel().setSelectionMode(SelectionMode.MULTI);
		
		GridView<CreditMemo> view = new BasicGridView<CreditMemo>();
		view.setEmptyText("There are no credit memos to display.");
		view.setAutoExpandColumn(column);
		grid.setView(view);
		
		// Add a listener to the grid
		grid.getSelectionModel().addSelectionChangedHandler(new SelectionChangedHandler<CreditMemo>() {
			@Override
			public void onSelectionChanged(SelectionChangedEvent<CreditMemo> event) {
				onGridSelectionChanged(event);
			}
		});
		
		return grid;
	}
	
	// Logic %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	void onGridSelectionChanged(SelectionChangedEvent<CreditMemo> event) {
		final CreditMemo creditMemo = grid.getSelectionModel().getSelectedItem();
		if (creditMemo == null)
			return;
		
		if (driver.isDirty()) { // If there are unsaved changes in the form
			UI.confirm("Unsaved Changes", "There are unsaved changes. Would you like to continue loading?",
				new ConfirmDialogHandler() {
					@Override
					public void onYes(HideEvent event) {
						edit(creditMemo);
					}
					
					public void onCancel(HideEvent event) {
						// just close the message box
					}
					
					public void onNo(HideEvent event) {
						// previously selected item should remain selected 
					}
				}
			);
		} else {
			edit(creditMemo);
		}
	}
	
	/**
	 * Loads <tt>creditMemo</tt> into the form editor.
	 * 
	 * @param creditMemo
	 */
	private void edit(final CreditMemo creditMemo) {
		driver.edit(creditMemo);
		
		saveBtn.setEnabled(creditMemo != null);
		cancelBtn.setEnabled(creditMemo != null);
	}
	
	// Listeners %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	@UiHandler("statusMenu")
	void onStatusSelection(SelectionEvent<Item> e) {
		loadData();
	}
	
	// Called when the 'Add' button is clicked
	@UiHandler("addBtn")
	void addClicked(SelectEvent e) {
		Window w = (Window) new CreateCreditMemoWindow().asWidget();
		w.show();
	}
	
	// Called when the 'Post' button is clicked
	@UiHandler("postBtn")
	void postClicked(SelectEvent e) {
		List<CreditMemo> selected = grid.getSelectionModel().getSelectedItems();
		if (selected.isEmpty()) {
			Notifications.info("Please select at least one credit memo.");
			return;
		}
		
		mainPanel.mask("Posting credit memos...");
		SalesServices.creditMemoSvc().postCreditMemos(selected, new Callback<List<CreditMemo>>(mainPanel) {
			@Override
			protected void handleSuccess(List<CreditMemo> result) {
				for (CreditMemo memo : result)
					grid.getStore().update(memo);
			}
		});
	}
	
	@UiHandler("moreBtnMenu")
	void onMenuSelection(SelectionEvent<Item> e) {
		Item item = e.getSelectedItem();
		if (item == refreshMenuItem) {
			refreshClicked();
		} else if (item == deleteMenuItem) {
			deleteClicked();
		} 
	}
	
	// Called when the 'Refresh' button is clicked
	void refreshClicked() {
		loadData();
	}
	
	// Called when the 'Delete' button is clicked
	void deleteClicked() {
		final CreditMemo selected = grid.getSelectionModel().getSelectedItem();
		if (selected == null)
			return;
		
		UI.confirm("Confirm Delete", "Are you sure you want to delete '" + selected.getCreditMemoNo() + "'?",
			new ConfirmDialogHandler() {
				@Override
				public void onYes(HideEvent event) {
					UI.mask(mainPanel, "Deleting " + selected.getCreditMemoNo() + "...");
					creditMemoSvc().delete(selected, new Callback<CreditMemo>(mainPanel) {
						@Override
						protected void handleSuccess(CreditMemo result) {
							grid.getStore().remove(result);
							
							// Clear the form editor if necessary
							CreditMemo inEditor = driver.flush();
							if (inEditor != null && inEditor.getCreditMemoNo().equals(result.getCreditMemoNo()))
								edit(null);
						}
					});
				}
			}
		);
	}
	
	// Called when the 'Save' button is clicked
	@UiHandler("saveBtn")
	void saveClicked(SelectEvent e) {
		CreditMemo memo = driver.flush();
		if (driver.hasErrors())
			return;
		
		String message = DataUtils.checkCreditMemo(memo);
		if (message != null) {
			Notifications.info(message);
			return;
		}
		
		UI.mask(mainPanel, "Updating credit memo...");
		creditMemoSvc().update(memo, new Callback<CreditMemo>(mainPanel) {
			@Override
			protected void handleSuccess(CreditMemo result) {
				grid.getStore().update(result);
				edit(result);
			}
		});
	}
	
	// Called when the 'Cancel' button is clicked
	@UiHandler("cancelBtn")
	void cancelClicked(SelectEvent e) {
		edit(null);
	}
	 
	// ITabItemPanel Methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	@Override
	public String getPanelId() {
		return SalesTasks.CREDIT_MEMOS.getId();
	}
	
	@Override
	public TabItemConfig getConfig() {
		if (config == null) {
			config = new TabItemConfig("Credit Memos", true);
			config.setIcon(SalesResources.INSTANCE.creditMemos());
		}
		return config;
	}
	
	@Override
	public void loadData() {
		Log.debug("Loading companies, customers, products for dropdown...");

		UI.mask(company, "Loading company...");
		companySvc().getNameAndIdOnly(new Callback<List<Company>>(company) {
			@Override
			protected void handleSuccess(List<Company> result) {
				company.getStore().clear();
				company.getStore().addAll(result);
			}
		});
		
		UI.mask(customer, "Loading customers...");
		customerSvc().getCustomerNameAndIdOnly(new Callback<List<Customer>>(customer) {
			@Override
			protected void handleSuccess(List<Customer> result) {
				customer.getStore().clear();
				customer.getStore().addAll(result);
			}
		});
		
		// Load data
		Log.debug("Loading Credit Memos...");
		loader.load();
		edit(null);
	}
	
	// Helper Methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	void setFilterInfo(TransactionLoadConfig config) {
		// Status
		if (pendingOnlyMenuItem.isChecked())
			config.setStatuses(TransactionStatus.PENDING);
		else if (postedOnlyMenuItem.isChecked())
			config.setStatuses(TransactionStatus.POSTED);
		else
			config.setStatuses((List<TransactionStatus>) null);
	}
	
}
